package com.muyi.controller;

import com.muyi.mapper.AccountMapper;
import com.muyi.pojo.entity.Result;
import com.muyi.pojo.entity.Account;
import com.muyi.utils.JwtUtils;
import com.muyi.utils.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import java.util.concurrent.TimeUnit;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "登录模块")
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api")
@Tag(name = "登录模块", description = "登录相关接口")
public class LoginController {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ApiOperation(value = "管理员登录")
    @PostMapping("/login")
    public Result login(@RequestBody Account account) {
        log.info("管理员登录: {}", account);
        Account e = accountMapper.getByAccountname(account);

        if (e == null) {
            throw new RuntimeException("管理员不存在");
        }

        // 对密码进行md5加密
        String s1 = MD5Util.getMD5String(account.getPassword());
        String pwdJM = MD5Util.getMD5String(s1 + MD5Util.SALT);


        // 比较密码（实际应使用 BCrypt 等加密方式）
        if (!e.getPassword().equals(pwdJM)) {
            throw new RuntimeException("密码错误");
        }

        // 密码正确
        // 登录成功,生成令牌,下发令牌
        // 通过令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("account_id", e.getAccount_id());
        claims.put("accountname", e.getAccountname());
        String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登录的员工信息

        // 刷新令牌
        claims.put("status", e.getStatus());
        String refresh_token = JwtUtils.generateJwt(claims);

        // 将token存入redis
        redisTemplate.opsForValue().set("access_token:" + e.getAccount_id(), jwt, 1, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set("refresh_token:" + e.getAccount_id(), refresh_token, 900, TimeUnit.MINUTES);


        // 将通过令牌和刷新令牌存入到一个json字符串中返回
        Map<String, String> map = new HashMap<>();
        map.put("access_token", jwt);
        map.put("refresh_token", refresh_token);

        return Result.success(map);

    }

    @ApiOperation(value = "管理员注册")
    @PostMapping("/reg")
    public Result register(@RequestBody Account account) {
        log.info("管理员注册: {}", account);
        account.setPassword(MD5Util.getMD5String(account.getPassword() + MD5Util.SALT));
        accountMapper.insert(account);
        return Result.success();
    }
}
